package com.gitee.candy.other;

import java.lang.reflect.Array;
import java.lang.reflect.Field;

/**
 * @author ：suyanlong
 * @date ：Created in 2020/10/12 20:38
 * @description：打印
 * @version: V1.0
 * 1.打印实体
 */
public class SysOutUtils {

    public static String printEntity(Object o) {
        return dump(o);
    }

    /**
     * 打印实体
     *
     * @param o
     * @return
     */
    private static String dump(Object o) {
        StringBuffer buffer = new StringBuffer();
        Class<?> oClass = o.getClass();
        if (oClass.isArray()) {
            buffer.append("[");
            for (int i = 0; i < Array.getLength(o); i++) {
                if (i > 0)
                    buffer.append(",");
                Object value = Array.get(o, i);
                buffer.append(value.getClass().isArray() ? dump(value) : value);
            }
            buffer.append("]");
        } else {
            buffer.append("{");
            while (oClass != null) {
                Field[] fields = oClass.getDeclaredFields();
                for (int i = 0; i < fields.length; i++) {
                    if (buffer.length() > 1)
                        buffer.append(",");
                    fields[i].setAccessible(true);
                    buffer.append(fields[i].getName());
                    buffer.append("=");
                    try {
                        Object value = fields[i].get(o);
                        if (value != null) {
                            buffer.append(value.getClass().isArray() ? dump(value)
                                    : value);
                        }
                    } catch (IllegalAccessException e) {
                    }
                }
                oClass = oClass.getSuperclass();
            }
            buffer.append("}");
        }
        return buffer.toString();
    }
}
